package com.hung.view.page;

import com.hung.pojo.Account;
import com.hung.pojo.Comment;
import com.hung.pojo.Matter;
import com.hung.pojo.User;
import com.hung.service.UserService;
import com.hung.service.serviceImpl.CommentServiceImpl;
import com.hung.service.serviceImpl.MatterServiceImpl;
import com.hung.service.serviceImpl.UserServiceImpl;
import com.hung.util.ListToVector;
import com.hung.util.aop.ServiceFactory;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Vector;

/**
 * 双击事件进去相应页面
 *
 * @author Hung
 */
public class MatterComponent extends Box {

    private JTable table;
    private Vector<String> title = new Vector<>();
    private Vector<Vector> data = new Vector<>();
    private DefaultTableModel tableModel;

    MatterServiceImpl matterService = new MatterServiceImpl();
    CommentServiceImpl commentService = new CommentServiceImpl();

    JPanel topPanel = new JPanel();
    JButton back = new JButton("返回");
    JButton praiseBtn = new JButton("点赞");
    JButton cancelPraiseBtn = new JButton("取消点赞");
    JButton favoriteBtn = new JButton("收藏");
    JButton cancelFavoriteBtn = new JButton("取消收藏");
    JButton reportBtn = new JButton("举报");
    JButton deleteBtn = new JButton("删除");
    JButton comment = new JButton("评论");
    JButton returnBtn = new JButton("返回");

    UserService userService = new ServiceFactory<>(new UserServiceImpl()).getService();

    public MatterComponent(Account account, Matter matter, JFrame jf, JSplitPane splitPane, int pid) {
        super(BoxLayout.Y_AXIS);

        Box box = Box.createVerticalBox();

        //组成头部组件
        User user = userService.queryUserById(account.getId());
        JLabel posterLabel = new JLabel(user.getNickName());
        JLabel postTimeLabel = new JLabel(matter.getPostTime());
        JLabel praiseNum = new JLabel("赞：" + matter.getPraise());


        //给一些按钮添加功能

        //返回键
        back.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                splitPane.setRightComponent(new PartComponent(pid, account, jf, splitPane));
            }
        });

        //赞按钮
        praiseBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                synchronized (matterService){
                    if (matterService.praise(user.getId(), matter.getId())) {
                        addComponent(posterLabel, postTimeLabel, praiseNum, account, matter);
                    }
                }
            }
        });

        //取消赞按钮
        cancelPraiseBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (matterService.cancelPraise(user.getId(), matter.getId())) {
                    addComponent(posterLabel, postTimeLabel, praiseNum, account, matter);
                }
            }
        });

        //收藏按钮
        favoriteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (matterService.favorite(user.getId(), matter.getId())) {
                    addComponent(posterLabel, postTimeLabel, praiseNum, account, matter);
                    JOptionPane.showMessageDialog(jf, "收藏成功！");
                }
            }
        });

        //取消收藏按钮
        cancelFavoriteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (matterService.cancelFavorite(user.getId(), matter.getId())) {
                    addComponent(posterLabel, postTimeLabel, praiseNum, account, matter);
                    JOptionPane.showMessageDialog(jf, "已取消收藏");
                }
            }
        });

        //举报按钮
        reportBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (matterService.report(matter.getId(), matter.getPid())) {
                    JOptionPane.showMessageDialog(jf, "举报成功!");
                }
            }
        });

        //删除按钮
        deleteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (matterService.deleteMatterById(matter.getId())) {
                    JOptionPane.showMessageDialog(jf, "删除成功！");
                    splitPane.setRightComponent(new PartComponent(pid, account, jf, splitPane));
                }
            }
        });

        //评论按钮
        comment.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new CommentDialog(jf, "发表你的评论", true, account, matter.getId()).show();
            }
        });

        //返回按钮
        returnBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                splitPane.setRightComponent(new PartComponent(pid, account, jf, splitPane));
            }
        });

        //初始化组件
        addComponent(posterLabel, postTimeLabel, praiseNum, account, matter);

        //主页组件
        JTextArea content = new JTextArea();
        content.setText(matter.getContent());
        content.setEditable(false);

        //组装评论区表格
        String[] titles = {"评论id", "用户", "评论", ""};
        for (String t : titles) {
            title.add(t);
        }

        //查询所有评论
        //TODO 右侧加入删除按钮
        List<Comment> comments = commentService.queryAllCommentsByMid(matter.getId());
        Vector<Vector> vectors = ListToVector.cListToVector(comments);
        data.clear();
        for (Vector vector : vectors) {
            data.add(vector);
        }


        //初始化页面
        tableModel = new DefaultTableModel(data, title);
        //设置table
        table = new JTable(tableModel);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        if (account.getRid() == 1 || account.getId() == matter.getUid()) {
            //增加删除按钮
            table.getColumnModel().getColumn(3).setCellEditor(new MyRender());
            table.getColumnModel().getColumn(3).setCellRenderer(new MyRender());
        }

        box.add(topPanel);
        box.add(content);
        box.add(new JScrollPane(table));
        this.add(box);
    }

    /**
     * 重绘组件
     *
     * @param posterLabel
     * @param postTimeLabel
     * @param praiseNum
     * @param account
     * @param matter
     */
    public void addComponent(JLabel posterLabel, JLabel postTimeLabel, JLabel praiseNum, Account account, Matter matter) {
        //重绘panel
        topPanel.removeAll();
        praiseNum = new JLabel("赞：" + matter.getPraise());

        //添加组件
        topPanel.add(posterLabel);
        topPanel.add(postTimeLabel);
        topPanel.add(praiseNum);
        //是否点赞给予不同按钮
        if (matterService.isPraise(account.getId(), matter.getId())) {
            topPanel.add(cancelPraiseBtn);
        } else {
            topPanel.add(praiseBtn);
        }
        if (matterService.isCollected(account.getId(), matter.getId())) {
            topPanel.add(cancelFavoriteBtn);
        } else {
            topPanel.add(favoriteBtn);
        }
        topPanel.add(reportBtn);
        if (matter.getUid() == account.getId() || account.getRid() == 1) {
            topPanel.add(deleteBtn);
        }
        topPanel.add(comment);
        topPanel.add(returnBtn);
        topPanel.repaint();
    }

    /**
     * 渲染器 编辑器
     */
    class MyRender extends AbstractCellEditor implements TableCellRenderer, ActionListener, TableCellEditor {

        private static final long serialVersionUID = 1L;
        private JButton button = null;

        public MyRender() {
            button = new JButton("删除");
            button.addActionListener(this);
        }

        @Override
        public Object getCellEditorValue() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus, int row, int column) {
            // TODO Auto-generated method stub
            return button;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            int i = JOptionPane.showConfirmDialog(null, "你确定要删除吗？");
            if (i == JOptionPane.OK_OPTION) {
                //获取id删除
                String id = (String) table.getValueAt(table.getSelectedRow(), 0);
                if (new CommentServiceImpl().deleteCommentById(Integer.parseInt(id))) {
                    //删除成功
                    tableModel.removeRow(table.getSelectedRow());
                    JOptionPane.showMessageDialog(null, "删除成功！");
                }
            }

        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            // TODO Auto-generated method stub
            return button;
        }

    }
}
